﻿using Newtonsoft.Json.Linq;
using OSGeo.OGR;
using System.Diagnostics;

namespace ZhZyz.Gdal
{
    public class MyGdalHelper
    {
        public MyGdalHelper()
        {
           // OSGeo.GDAL.Gdal.AllRegister();
            GdalConfiguration.ConfigureOgr();
            
        }

        /// <summary>
        ///     添加数据
        /// </summary>
        /// <param name="datafile">数据文件路径</param>
        /// <param name="layerName">图层</param>
        /// <param name="geojsons">json格式/WKT</param>
        public void AppendData(string datafile,  string layerName, string[] geojsons,bool iswkt=false)
        {
            if (geojsons.Length == 0) return;
            var jo = JObject.Parse(geojsons[0]);
            var geojs = jo["geometry"];
            int geotype = 0;
            if (iswkt)
            {

                if (geojs.ToString().StartsWith("POINT"))
                    geotype = 1;
                else if (geojs.ToString().StartsWith("LINESTRING"))
                        geotype = 2;
                else 
                        geotype = 3;
 
            }
            else
            {
                var property1 = geojs["type"];
                switch (property1.Value<string>())
                {
                    case "Point":
                        geotype = 1;
                        break;
                    case "LineString":
                        geotype = 2;
                        break;
                    case "Polygon":
                        geotype = 3;
                        break;
                    default:
                        break;
                }
            }
         

            var dataSource = GdalService.OpenDataSource(datafile);
            if (dataSource == null)
            {
                Trace.WriteLine($"打开数据库失败！");
                return;
            }
            //dataSource.StartTransaction(1 );
            var layer = GdalService.GetLayer(dataSource, layerName, geotype,out bool isNew);
            if (isNew)
            {
                //添加字段
                foreach (var item in jo["properties"])
                {
                    GeomFieldDefn geomFieldDefn = new GeomFieldDefn("", geotype==1?wkbGeometryType.wkbPoint:geotype==2? wkbGeometryType.wkbLineString:wkbGeometryType.wkbPolygon);
                    layer.CreateGeomField(geomFieldDefn, 1);
                    JProperty property =(JProperty) item;
                    //item.Type == JTokenType.String
                    FieldDefn fieldDefn = new FieldDefn(property.Name,FieldType.OFTString);
                    layer.CreateField(fieldDefn,1);
                }
        
            }
            layer.StartTransaction();
            //添加要素
            foreach (var item in geojsons)
            {
                jo = JObject.Parse(item);
                geojs = jo["geometry"];

                Feature feature = new Feature(layer.GetLayerDefn());
              

                foreach (var item1 in jo["properties"])
                {
                    JProperty property = (JProperty)item1;
                    feature.SetField(property.Name, property.Value.ToString());
                }
                var wktjson = geojs.ToString();
                var geo = iswkt?Ogr.CreateGeometryFromWkt(ref wktjson, null):  Ogr.CreateGeometryFromJson(wktjson);
                feature.SetGeometry(geo);
                layer.CreateFeature(feature);
                
            }
            layer.CommitTransaction();
            //dataSource.CommitTransaction();
            dataSource.SyncToDisk();
            dataSource.Dispose();
        }
    }
}